package cn.hd01.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.common.BaseConstant.backendType;
import cn.hd01.repository.entity.BookRecord;
import cn.hd01.repository.entity.User;
import cn.hd01.service.BookRecordService;
import cn.hd01.service.CustomerService;
import cn.hd01.util.CommonUtil;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebConstant;

@Controller
@RequestMapping("/bookRecord")
@Auth
public class BookRecordController {
	@Autowired
	private BookRecordService bookRecordService;
	@Autowired
	private CustomerService customerService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model m, HttpServletRequest request) {
		return "bookRecord";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<BookRecord> find(BookRecord b, @PageableDefault Pageable pageable, HttpServletRequest req) {
		
		User loginUser = (User) req.getSession().getAttribute(WebConstant.USER_SESSION_NAME);
		Integer type = CommonUtil.getLoginUserType(loginUser);

		if(backendType.TEACHER.equals(type)){
			List<Integer> distributorIdList = customerService.findDistributorIdByServantId(loginUser.getId());
			if(CollectionUtils.isEmpty(distributorIdList)){
				return new PageImpl<BookRecord>(new ArrayList<BookRecord>());
			}else{
				b.setDistributorIdList(distributorIdList);
			}
		} 
		Page<BookRecord> result = bookRecordService.findAll(b, pageable);
		return result; 
	}

	@ResponseBody
	@RequestMapping(path = "/delete/{id}", method = RequestMethod.GET)
	private void delete(@PathVariable("id") Integer id) {
		bookRecordService.delete(id);
	}

}
